﻿using System;
using System.IO;
using Jink.Core.Json;

namespace Jink.Playground.MockData
{
    internal static class Database
    {
        public static PdpList Pdp { get { return Load(); } }

        public static String PdpFileName { get { return @".\pdp.json"; } }
        private static void EnsureDatabase()
        {
            if (!File.Exists(PdpFileName))
            {
                using (var resource = typeof(PdpList).Assembly
                    .GetManifestResourceStream("Jink.Playground.MockData.pdp.json"))
                {
                    var content = new StreamReader(resource).ReadToEnd();
                    File.WriteAllText(PdpFileName, content);
                }
            }
        }

        private static PdpList Load()
        {
            EnsureDatabase();
            var db = File.ReadAllText(PdpFileName);
            return db.ParseJson().FromJson<PdpList>();
        }

        public static void Save(this PdpList pdp)
        {
            EnsureDatabase();
            var db = pdp.ToJson().ToString();
            File.WriteAllText(PdpFileName, db);
        }
    }
}
